var imageOffsetX, imageOffsetY;
var c;
var _config;

// 初始化canvas
function initCanvas() {
    $('.canvas-container').each(function (index) {

        var canvasContainer = $(this)[0];
        var canvasObject = $("canvas", this)[0];
        var url = $(this).data('floorplan');
        c = new fabric.Canvas(canvasObject);

        // undo/redo
        _config = {
            canvasState             : [],
            currentStateIndex       : -1,
            undoStatus              : false,
            redoStatus              : false,
            undoFinishedStatus      : 1,
            redoFinishedStatus      : 1,
            undoButton              : document.getElementById('undo'),
            redoButton              : document.getElementById('redo'),
        };

        // 画板设置
        c.setHeight($(canvasContainer).height());
        c.setWidth($(canvasContainer).width());
        c.setBackgroundImage(url, c.renderAll.bind(c));

        function handleDragOver(e) {
            if (e.preventDefault) {
                e.preventDefault();
            }
            e.dataTransfer.dropEffect = 'copy';
            return false;
        }

        function handleDragEnter(e) {
            this.classList.add('over');
        }

        function handleDragLeave(e) {
            this.classList.remove('over');
        }

        function handleDrop(e) {
            e = e || window.event;
            if (e.preventDefault) {
                e.preventDefault();
            }
            if (e.stopPropagation) {
                e.stopPropagation();
            }
            var img = document.querySelector('.furniture img.img_dragging');
            // 拖拽的元素非图片
            if (img == null || typeof img == undefined) {
                return false;
            }
            materialIds.push($(img).attr("id"));
            var totalPrice = Number($("#price").val());
            var price = Number($(img).attr("price"));
            $("#price").val(totalPrice + price);

            var offset = $(canvasObject).offset();
            var y = e.clientY - (offset.top + imageOffsetY);
            var x = e.clientX - (offset.left + imageOffsetX);

            var height = img.naturalHeight;
            var width = img.naturalWidth;
            var scan = width/height;
            var canvasWidth = $("#canvas").width();
            var imgWidth = canvasWidth/3;
            var imgHeight = imgWidth / scan;

            // 从URL加载图片
            // var url = "http://47.106.163.114/images/20180831_1535701808509_VEIyazdVVEo0V1lCdU5qeTF6a1hYWEdHcFhhXyEhMjA3MjEzNjAyNS5wbmc=.png";
            // fabric.Image.fromURL(url, function (newImage) {
            //     newImage.setWidth(247);
            //     newImage.setHeight(162.09375);
            //     c.add(newImage);
            // }, {left: 367.42201358207313, angle: 44.18308155175003, top: 169.85308617871638, crossOrigin: "anonymous", "cornerSize":6, "cornerColor": "#4A3A3A", "borderColor": "#4A3A3A", "_price": 100});

            fabric.Image.fromURL(img.src, function (newImage) {
                newImage.setWidth(imgWidth);
                newImage.setHeight(imgHeight);
                c.add(newImage);
            }, {left: x, top: y, crossOrigin: "anonymous", "cornerSize":6, "cornerColor": "#4A3A3A", "borderColor": "#4A3A3A", "_price": price, "id": $(img).attr("id")});

            // angle: -45角度
            return false;
        }

        bindImageDrag();
        canvasContainer.addEventListener('dragenter', handleDragEnter, false);
        canvasContainer.addEventListener('dragover', handleDragOver, false);
        canvasContainer.addEventListener('dragleave', handleDragLeave, false);
        canvasContainer.addEventListener('drop', handleDrop, false);
        c.on('object:selected', onObjectSelected);
        c.on('selection:cleared', function () {
            $("#tools").css("visibility", "hidden");
        });

        /* 添加对象 */
        c.on(
            'object:modified', function(){
                updateCanvasState();
            }
        );
        /* 修改对象 */
        c.on(
            'object:added', function(){
                updateCanvasState();
            }
        );

        // 选中事件
        function onObjectSelected(e) {

            // canvas.getActiveObject()
            // canvas.sendBackwards(t) //向下跳一层
            // canvas.sendToBack(t)    //向下跳底层：
            // canvas.bringForward(t)  //向上跳一层：
            // canvas.bringToFront(t)  //向上跳顶层：
            // target.remove() 删除选中

            /*
            canvas.sendBackwards(target);

            console.info(index);*/

            // 获取所有对象
            // var objects = c.getObjects();
            // c.forEachObject(function (object) {
            //     console.info(c.getObjects().indexOf(object));
            //     c.moveTo(object, 0);
            //     console.info(c.getObjects().indexOf(object));
            // });

            var activeObject = c.getActiveObject();
            if (activeObject != null) {
                $("#tools").css("visibility", "visible");
            } else {
                $("#tools").css("visibility", "hidden");
            }
        }

        var updateCanvasState = function() {
            if((_config.undoStatus == false && _config.redoStatus == false)){
                var jsonData        = c.toJSON();
                var canvasAsJson        = JSON.stringify(jsonData);
                if(_config.currentStateIndex < _config.canvasState.length-1){
                    var indexToBeInserted                  = _config.currentStateIndex+1;
                    _config.canvasState[indexToBeInserted] = canvasAsJson;
                    var numberOfElementsToRetain           = indexToBeInserted+1;
                    _config.canvasState                    = _config.canvasState.splice(0,numberOfElementsToRetain);
                }else{
                    _config.canvasState.push(canvasAsJson);
                }
                _config.currentStateIndex = _config.canvasState.length-1;
                if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
                    _config.redoButton.disabled= "disabled";
                }
            }
        }
    });
}

// 获取当前对象所属层
fabric.Object.prototype.getZIndex = function() {
    return this.c.getObjects().indexOf(this);
};

initCanvas();

function bindImageDrag() {
    var images = document.querySelectorAll('.furniture img');
    [].forEach.call(images, function (img) {
        img.addEventListener('dragstart', handleDragStart, false);
        img.addEventListener('dragend', handleDragEnd, false);
    });
}

// 针对图片
function handleDragStart(e) {
    var images = document.querySelectorAll('.furniture img');
    [].forEach.call(images, function (img) {
        img.classList.remove('img_dragging');
    });
    this.classList.add('img_dragging');

    var imageOffset = $(this).offset();
    imageOffsetX = e.clientX - imageOffset.left;
    imageOffsetY = e.clientY - imageOffset.top;
}

function handleDragEnd(e) {
    var images = document.querySelectorAll('.furniture img');
    [].forEach.call(images, function (img) {
        img.classList.remove('img_dragging');
    });
}

// canvas.sendBackwards(t) //向下跳一层
// canvas.sendToBack(t)    //向下跳底层：
// canvas.bringForward(t)  //向上跳一层：
// canvas.bringToFront(t)  //向上跳顶层：

/**
 * 向下跳一层
 */
function sendBackwards() {
    var activeObject = c.getActiveObject();
    if (!activeObject) {
        return;
    }
    c.sendBackwards(activeObject);
}

/**
 *向下跳底层
 */
function sendToBack() {
    var activeObject = c.getActiveObject();
    if (!activeObject) {
        return;
    }
    c.sendToBack(activeObject);
}

/**
 * 向上一层
 */
function bringForward() {
    var activeObject = c.getActiveObject();
    if (!activeObject) {
        return;
    }
    c.bringForward(activeObject);
}

/**
 * 顶层
 */
function bringToFront() {
    var activeObject = c.getActiveObject();
    if (!activeObject) {
        return;
    }
    c.bringToFront(activeObject);
}

function deleteObject() {
    var activeObject = c.getActiveObject();
    if (!activeObject) {
        return;
    }
    // 重新计算价格
    var price = activeObject._price;
    var totalPrice = Number($("#price").val());
    var p = totalPrice - price;
    if (p < 1) {
        p = 0;
    }
    $("#price").val(p);
    var id = activeObject.id;
    var index = $.inArray(id, materialIds);
    materialIds.splice(index,  1);
    c.remove(activeObject);
}

function undo() {
    if(_config.undoFinishedStatus){
        if(_config.currentStateIndex == -1){
            _config.undoStatus = false;
        }
        else{
            if (_config.canvasState.length >= 1) {
                _config.undoFinishedStatus = 0;
                if(_config.currentStateIndex != 0){
                    _config.undoStatus = true;
                    c.loadFromJSON(_config.canvasState[_config.currentStateIndex-1],function(){
                        var jsonData = JSON.parse(_config.canvasState[_config.currentStateIndex-1]);
                        c.renderAll();
                        _config.undoStatus = false;
                        _config.currentStateIndex -= 1;
                        _config.undoButton.removeAttribute("disabled");
                        if(_config.currentStateIndex !== _config.canvasState.length-1){
                            _config.redoButton.removeAttribute('disabled');
                        }
                        _config.undoFinishedStatus = 1;
                    });
                }
                else if(_config.currentStateIndex == 0){
                    c.clear();
                    _config.undoFinishedStatus = 1;
                    _config.undoButton.disabled= "disabled";
                    _config.redoButton.removeAttribute('disabled');
                    _config.currentStateIndex -= 1;
                }
            }
        }
    }
}

function redo() {
    if(_config.redoFinishedStatus){
        if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
            _config.redoButton.disabled= "disabled";
        }else{
            if (_config.canvasState.length > _config.currentStateIndex && _config.canvasState.length != 0){
                _config.redoFinishedStatus = 0;
                _config.redoStatus = true;
                c.loadFromJSON(_config.canvasState[_config.currentStateIndex+1],function(){
                    var jsonData = JSON.parse(_config.canvasState[_config.currentStateIndex+1]);
                    c.renderAll();
                    _config.redoStatus = false;
                    _config.currentStateIndex += 1;
                    if(_config.currentStateIndex != -1){
                        _config.undoButton.removeAttribute('disabled');
                    }
                    _config.redoFinishedStatus = 1;
                    if((_config.currentStateIndex == _config.canvasState.length-1) && _config.currentStateIndex != -1){
                        _config.redoButton.disabled= "disabled";
                    }
                });
            }
        }
    }
}